/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mangaviewer.servlet;

import com.mangaviewer.util.SearchConstants;
import com.mangaviewer.json.IOMangaJsonFile;
import com.mangaviewer.model.Manga;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 *
 * @author dorian
 */
@WebServlet(name = "SearchManga", urlPatterns = {"/searchmanga"})
public class SearchManga extends HttpServlet {

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP
   * <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException {
    Logger.getLogger(SearchManga.class.getName()).log(Level.INFO, "RequestURI: " + request.getRequestURI());
    String query = request.getParameter("q");
    if (query != null) {
      List<Manga> manga = new ArrayList<Manga>();
      try {
        manga = IOMangaJsonFile.read();
      } catch (FileNotFoundException ex) {
        Logger.getLogger(SearchManga.class.getName()).log(Level.SEVERE, "Manga.json file not found", ex);
      }

      if (manga.isEmpty()) {
        try {
          response.sendRedirect(SearchConstants.FETCH_MANGA_LIST_FROM_SERVER_URL + "?q=" + query);
        } catch (IOException ex) {
          Logger.getLogger(SearchManga.class.getName()).log(Level.SEVERE, "Could not redirect to " + SearchConstants.FETCH_MANGA_LIST_FROM_SERVER_URL, ex);
        }
      } else {
        try {
          manga = IOMangaJsonFile.read();
        } catch (FileNotFoundException ex) {
          Logger.getLogger(SearchManga.class.getName()).log(Level.SEVERE, "Manga.json file not found", ex);
        }

        Logger.getLogger(SearchManga.class.getName()).log(Level.INFO, "manga 0: " + manga.get(0));
      }
    }
  }

  /**
   * Returns a short description of the servlet.
   *
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Search Manga Eden database for manga";
  }// </editor-fold>
}
